﻿using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class DialogDrag : MonoBehaviour, IDragHandler,IPointerDownHandler {
     


    //当鼠标点击屏幕之后的逻辑，根据鼠标点击的位置和拖动之后的距离判断相应的移动
    RectTransform parentRTF,panelRTF; 
    void Start()
    { 
        parentRTF = this.transform.parent.GetComponent<RectTransform>();
        panelRTF = parentRTF.parent.GetComponent<RectTransform>();
    }

    //[ə'rɪdʒənl]
    Vector3 originalLocalPosition; //当前物体轴心点 相对于 父物体轴心点位置
    Vector2 originalPointerPosition;//光标点击时的 localPosition 
    public void OnPointerDown(PointerEventData eventData)
    {
        //记录父物体的自身坐标
        originalLocalPosition = parentRTF.localPosition;
        //将点击的屏幕坐标 转换为 localPosition
        RectTransformUtility.ScreenPointToLocalPointInRectangle
            (panelRTF, eventData.position, eventData.pressEventCamera, out originalPointerPosition);
    }

   public Vector2 leftSpace,rightSpace;
    public void OnDrag(PointerEventData eventData)
    { 
        //获取拖拽时光标 的localPosition值
        Vector2 localPointerPosition;
        if (RectTransformUtility.ScreenPointToLocalPointInRectangle
            (panelRTF, eventData.position, eventData.pressEventCamera, out localPointerPosition))
        {
            Vector3 positionOffset = localPointerPosition - originalPointerPosition;
           parentRTF .localPosition = originalLocalPosition + positionOffset;
        }

        LimitPosition();
    }

    private void LimitPosition()
    {
        Vector3 position = parentRTF.localPosition;
        //面板 轴心点 距 左下角 坐标  -    父物体 轴心点 距 左下角 坐标
        leftSpace = panelRTF.rect.min - parentRTF.rect.min;
        rightSpace = panelRTF.rect.max - parentRTF.rect.max;

        position.x = Mathf.Clamp(parentRTF.localPosition.x, leftSpace.x, rightSpace.x);
        position.y = Mathf.Clamp(parentRTF.localPosition.y, leftSpace.y, rightSpace.y);

        parentRTF.localPosition = position;
    } 
}
